const db = require('../config/database');
const moment = require('moment');

class MpUser {
  static async findAll(page = 1, limit = 10, searchParams = {}) {
    const offset = (page - 1) * limit;
    let query = 'SELECT * FROM mpuser WHERE 1=1';
    const params = [];
    
    if (searchParams.id) {
      query += ' AND id = ?';
      params.push(searchParams.id);
    }
    if (searchParams.nickname) {
      query += ' AND nickname LIKE ?';
      params.push(`%${searchParams.nickname}%`);
    }
    if (searchParams.appid) {
      query += ' AND appid = ?';
      params.push(searchParams.appid);
    }
    if (searchParams.openid) {
      query += ' AND openid = ?';
      params.push(searchParams.openid);
    }
    if (searchParams.unionid) {
      query += ' AND unionid = ?';
      params.push(searchParams.unionid);
    }
    if (searchParams.status) {
      query += ' AND status = ?';
      params.push(searchParams.status);
    }
    if (searchParams.tag) {
      query += ' AND tag LIKE ?';
      params.push(`%${searchParams.tag}%`);
    }
    if (searchParams.createAt) {
      query += ' AND createAt LIKE ?';
      params.push(`%${searchParams.createAt}%`);
    }
    
    query += ' ORDER BY createAt DESC LIMIT ? OFFSET ?';
    params.push(limit, offset);

    console.log('SQL查询:', query, params);
    
    return new Promise((resolve, reject) => {
      db.all(query, params, (err, rows) => {
        if (err) {
          console.error('查询失败:', err);
          reject(err);
        } else {
          console.log(`查询到${rows?.length || 0}条记录`);
          resolve(rows || []);
        }
      });
    });
  }

  static async count(searchParams = {}) {
    let query = 'SELECT COUNT(*) as total FROM mpuser WHERE 1=1';
    const params = [];
    
    if (searchParams.id) {
      query += ' AND id = ?';
      params.push(searchParams.id);
    }
    if (searchParams.nickname) {
      query += ' AND nickname LIKE ?';
      params.push(`%${searchParams.nickname}%`);
    }
    if (searchParams.appid) {
      query += ' AND appid = ?';
      params.push(searchParams.appid);
    }
    if (searchParams.openid) {
      query += ' AND openid = ?';
      params.push(searchParams.openid);
    }
    if (searchParams.unionid) {
      query += ' AND unionid = ?';
      params.push(searchParams.unionid);
    }
    if (searchParams.status) {
      query += ' AND status = ?';
      params.push(searchParams.status);
    }
    if (searchParams.tag) {
      query += ' AND tag LIKE ?';
      params.push(`%${searchParams.tag}%`);
    }
    if (searchParams.createAt) {
      query += ' AND createAt LIKE ?';
      params.push(`%${searchParams.createAt}%`);
    }

    console.log('COUNT查询:', query, params);

    return new Promise((resolve, reject) => {
      db.get(query, params, (err, row) => {
        if (err) {
          console.error('统计失败:', err);
          reject(err);
        } else {
          console.log('总记录数:', row?.total);
          resolve(row?.total || 0);
        }
      });
    });
  }

  static create(user) {
    return new Promise((resolve, reject) => {
      const sql = `
        INSERT OR REPLACE INTO mpuser 
        (nickname, openid, appid, status, photo, country, province, city, unionid, tag, createAt)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `;
      
      db.run(sql, [
        user.nickname,
        user.openid,
        user.appid,
        user.status || '0',
        user.photo || '',
        user.country || '',
        user.province || '',
        user.city || '',
        user.unionid || '',
        user.tag || '',
        user.createAt || new Date().toISOString()
      ], function(err) {
        if (err) {
          console.error('保存用户失败:', err);
          reject(err);
        } else {
          resolve(this.lastID);
        }
      });
    });
  }

  static async update(id, mpUserData) {
    const fields = Object.keys(mpUserData);
    const values = Object.values(mpUserData);
    const setClause = fields.map(field => `${field} = ?`).join(',');
    
    return new Promise((resolve, reject) => {
      db.run(
        `UPDATE mpuser SET ${setClause} WHERE id = ?`,
        [...values, id],
        (err) => {
          if (err) reject(err);
          resolve(true);
        }
      );
    });
  }

  static async delete(id) {
    return new Promise((resolve, reject) => {
      db.run('DELETE FROM mpuser WHERE id = ?', [id], (err) => {
        if (err) reject(err);
        resolve(true);
      });
    });
  }
}

module.exports = MpUser; 